package com.garlic.face.jlf.ui;

import android.app.Fragment;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.garlic.face.jlf.App;
import com.garlic.face.jlf.R;
import com.garlic.face.jlf.base.BaseActivity;
import com.garlic.face.jlf.transaction.Means;
import com.garlic.face.jlf.transaction.balance.ReadSerialPort;
import com.garlic.face.jlf.transaction.balance.ScaleUtil;
import com.garlic.face.jlf.transaction.balance.SerialPortFunction;
import com.garlic.face.jlf.transaction.balance.cclhelper.GoodsHelper;
import com.garlic.face.jlf.transaction.balance.database.GoodsWeight;
import com.garlic.face.jlf.utils.ToastUtils;
import com.garlic.face.jlf.utils.Tools;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScaleSettingActivity extends BaseActivity implements View.OnClickListener, ReadSerialPort.DataWeight {
    private static final String TAG = "ScaleSettingActivity";
    private Button mBtnClose;
    private EditText mWeightInput;
    private LinearLayout mScaleSettingLayout;
    boolean blScaleEvent = false; //true-允许触发电子称事件
//    private NormalDialog confirmDlg;
    private CommonDialog mCommonDialog;
    private SerialPortFunction serialPortFunction;
    private ExecutorService executorService;
    private CountDownTimer mTimer;//倒计时
    private TextView mTimeText;
    private boolean isTimming;//true--正在倒计时，不能操作
    private Switch mSwitchBtn;
    private EditText goodsBarcodeEdt;
    private Button btnupdateGoodsWeight;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        blScaleEvent = true;
        isTimming = false;
        setContentView(R.layout.fragment_scale_setting);
        init();
        serialPortFunction = SerialPortFunction.getInstance();
        serialPortFunction.setContext(this);
        executorService = Executors.newCachedThreadPool();
        blScaleEvent = true;
        serialPortFunction.startSerialReadEle(this);
        mBtnClose.setClickable(true);

    }


    private void init() {
        mScaleSettingLayout = (LinearLayout) findViewById(R.id.scale_setting_layout);
        mBtnClose = (Button)findViewById(R.id.scale_setting_close);
        Button btnSetZero = (Button)findViewById(R.id.scale_setZero_button);
        Button btnSetWeight = (Button)findViewById(R.id.scale_setWeight_button);
        mWeightInput = (EditText)findViewById(R.id.scale_input);
        mWeightInput.setInputType(InputType.TYPE_CLASS_NUMBER);
        Button btnScaleZero = (Button)findViewById(R.id.scale_Zero_button);
        Button btnScalePeel = (Button)findViewById(R.id.scale_Peel_button);
        Button btnClearPeel = (Button)findViewById(R.id.scale_ClearPeel_button);
        mTimeText = (TextView) findViewById(R.id.scale_setting_time);
        mSwitchBtn = findViewById(R.id.swicth_btn);
        goodsBarcodeEdt = findViewById(R.id.goods_barcode_edt);
        goodsBarcodeEdt.setInputType(InputType.TYPE_CLASS_NUMBER);
        btnupdateGoodsWeight = findViewById(R.id.update_weight_btn);

        mScaleSettingLayout.setOnClickListener(this);
        mBtnClose.setOnClickListener(this);
        btnSetZero.setOnClickListener(this);
        btnSetWeight.setOnClickListener(this);
        btnScaleZero.setOnClickListener(this);
        btnScalePeel.setOnClickListener(this);
        btnClearPeel.setOnClickListener(this);
        btnupdateGoodsWeight.setOnClickListener(this);

        mSwitchBtn.setChecked(Means.blAssistMode);
        mSwitchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                //控制开关字体颜色
                Means.blAssistMode = b;
                Tools.setNeedCloseWeight(b);
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.scale_setting_close:
                if(isTimming){
                    ToastUtils.toastShow("正在进行标定，请勿关闭！", ToastUtils.INFO);
                    break;
                }
                else{
                    finish();
                    break;
                }
            case R.id.scale_setZero_button:
                if(!blScaleEvent || isTimming)
                    break;
                else{
                    /*
                    confirmDlg = NormalDialog.newInstanceTwo("零点标定","请先清空称台上的商品，然后按“确定” 零点标定响应时间大约2秒。");
                    confirmDlg.setCallBackTwo(new NormalDialog.CallBackTwo() {
                        @Override
                        public void twoOk(View view) {
                            blScaleEvent = false;
                            ScaleUtil.ScaleZeroCalibration(serialPortFunction);
                            // 3秒倒计时
                            mTimer = new CountDownTimer(3 * 1000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                        mTimeText.setText(String.valueOf(millisUntilFinished / 1000));
                                }

                                @Override
                                public void onFinish() {
                                    Means.InitWeight = Means.weightqty;
                                    Means.TotalWeight = Means.InitWeight;
                                    blScaleEvent = true;
                                    isTimming = false;
                                    mTimeText.setText("");
                                    confirmDlg.dismiss();
                                }
                            }.start();
                        }

                        @Override
                        public void twoCancel(View view) {
                            confirmDlg.dismiss();
                        }
                    });
                    confirmDlg.show(getFragmentManager(),TAG);
                    */
                    mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "零点标定","请先清空称台上的商品，然后按“确定” 零点标定响应时间大约2秒。");
                    mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                        @Override
                        public void twoOk(View view) {
                            blScaleEvent = false;
                            ScaleUtil.ScaleZeroCalibration(serialPortFunction);
                            // 3秒倒计时
                            mTimer = new CountDownTimer(3 * 1000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    mTimeText.setText(String.valueOf(millisUntilFinished / 1000));
                                }

                                @Override
                                public void onFinish() {
                                    Means.InitWeight = Means.weightqty;
                                    Means.TotalWeight = Means.InitWeight;
                                    blScaleEvent = true;
                                    isTimming = false;
                                    mTimeText.setText("");
                                    mCommonDialog.dismiss();
                                }
                            }.start();
                        }

                        @Override
                        public void twoCancel(View view) {
                            mCommonDialog.dismiss();
                        }
                    });
                    mCommonDialog.show();
                    break;
                }
            case R.id.scale_setWeight_button:
                if(!blScaleEvent || isTimming){
                }
                else{
                    double weight = 0;

                    if(mWeightInput.getText().toString().isEmpty()){
                        ToastUtils.toastShow("请先输入标定重量", ToastUtils.ERROR);
                    }
                    else{
                        weight = Double.parseDouble(mWeightInput.getText().toString());
                        if(weight < 9 || weight > 30){

                            ToastUtils.toastShow("输入有误，范围9-30！", ToastUtils.ERROR);
                        }
                        else{
                            mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "量程标定", "请先将标准重量放置到装袋台，然后按“确定”。响应时间大约17秒");
                            double finalWeight = weight;
                            mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                                @Override
                                public void twoOk(View view) {
                                    int qty = BigDecimal.valueOf(finalWeight).multiply(BigDecimal.valueOf(1000)).intValue();
                                    String weightQty = new DecimalFormat("000000").format(qty);
                                    byte[] bytes = weightQty.getBytes();
                                    byte[] data = { 0x53, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x0D, 0x0A};
                                    for(int i=0; i<bytes.length; i++){
                                        data[i + 1] = bytes[i];
                                    }
                                    ScaleUtil.ScaleWeightCalibration(serialPortFunction, data);
                                    // 20秒倒计时
                                    mTimer = new CountDownTimer(20 * 1000, 1000) {
                                        @Override
                                        public void onTick(long millisUntilFinished) {
                                            mTimeText.setText(String.valueOf(millisUntilFinished / 1000));
                                        }

                                        @Override
                                        public void onFinish() {
                                            blScaleEvent = true;
                                            isTimming = false;
                                            mCommonDialog.dismiss();
                                            mTimeText.setText("");
                                        }
                                    }.start();
                                }

                                @Override
                                public void twoCancel(View view) {
                                    mCommonDialog.dismiss();
                                }
                            });
                            mCommonDialog.show();
                        }
                    }


                }
                break;
            case R.id.scale_Zero_button:
                if(isTimming){

                }
                else{
                    mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "电子秤清零","请先清空称台上的商品，然后按“确定”。");
                    mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                        @Override
                        public void twoOk(View view) {
                            ScaleUtil.ScaleZero(serialPortFunction);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Means.InitWeight = Means.weightqty;
                            Means.TotalWeight = Means.InitWeight;
                            mCommonDialog.dismiss();
                        }

                        @Override
                        public void twoCancel(View view) {
                            mCommonDialog.dismiss();
                        }
                    });
                    mCommonDialog.show();
                }
                break;
            case R.id.scale_Peel_button:
                if(isTimming){

                }
                else{
                    mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "电子秤去皮","确定执行电子称去皮操作吗？");
                    mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                        @Override
                        public void twoOk(View view) {
                            ScaleUtil.ScalePeel(serialPortFunction);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Means.InitWeight = Means.weightqty;
                            Means.TotalWeight = Means.InitWeight;
                            mCommonDialog.dismiss();
                        }

                        @Override
                        public void twoCancel(View view) {
                            mCommonDialog.dismiss();
                        }
                    });
                    mCommonDialog.show();
                }
                break;
            case R.id.scale_ClearPeel_button:
                if(isTimming){

                }
                else {
                    mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "电子秤清皮","确定执行电子称清皮操作吗？");
                    mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                        @Override
                        public void twoOk(View view) {
                            ScaleUtil.ScalePeelClear(serialPortFunction);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Means.InitWeight = Means.weightqty;
                            Means.TotalWeight = Means.InitWeight;
                            mCommonDialog.dismiss();
                        }

                        @Override
                        public void twoCancel(View view) {
                            mCommonDialog.dismiss();
                        }
                    });
                    mCommonDialog.show();
                }
                break;
            case R.id.update_weight_btn:
                updateGoodsWeight();
                break;
        }
    }

    private void updateGoodsWeight() {
        String code = goodsBarcodeEdt.getText().toString().trim();
        if(TextUtils.isEmpty(code) || code.length() <= 0){
            ToastUtils.toastShow("请输入正确条码", ToastUtils.ERROR);
        }else {
            List<GoodsWeight> goodsWeightList = GoodsHelper.getLikeGoodsWeightByBarcode(App.getInstances().getDaoSession().getGoodsWeightDao(), code);
            if(goodsWeightList != null && goodsWeightList.size() > 0){
                Double currentDBGoodWeight = goodsWeightList.get(0).getWeight();
                Double currentGoodWeight = Means.weightqty;
                /**********************************弹框提示确认重量***************************************/
                mCommonDialog = new CommonDialog(ScaleSettingActivity.this, "two", "设置商品重量","当前商品库重量为 " + currentDBGoodWeight + " kg, 确定将其修改为 "
                        + currentGoodWeight + " kg吗?");
                mCommonDialog.setCallBackTwo(new CommonDialog.CallBackTwo() {
                    @Override
                    public void twoOk(View view) {
                        GoodsHelper.UpdateGoodsWeight(App.getInstances().getDaoSession().getGoodsWeightDao(), code, currentGoodWeight);
                        ToastUtils.toastShow("修改完成", ToastUtils.SUCCESS);
                        mCommonDialog.dismiss();
                    }

                    @Override
                    public void twoCancel(View view) {
                        mCommonDialog.dismiss();
                    }
                });
                mCommonDialog.show();
            }else {
                ToastUtils.toastShow("商品库中不存在该商品", ToastUtils.ERROR);
            }
        }


    }

    @Override
    public void weight(String weight) {
        Means.weightqty = Double.parseDouble(weight);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialPortFunction.closeEle();
    }
}
